package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.medical.domain.BaseInpatient;
import org.brisling.medical.service.RecipelService;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryBaseInpatientService</p>
 * <p>Description: service</p>
 * <p>Company: tongking</p>
 * @author trastor
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午9:59:40
 */
@RestController
@RequestMapping("/baseInpatient/query")
public class QueryBaseInpatientService extends AbstractBaseQueryService<BaseInpatient>{
	
	
	@Autowired
	private QueryDictionaryService qryDictionaryService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;

	@Autowired
	private RecipelService qryService;
	
	public QueryBaseInpatientService(){
		this.moduleName = ConstSysParam.MODULE_BASE_INPATIENT;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = this.moduleName;
		this.clazz = BaseInpatient.class;
		typeMap = this.getTypeMap(clazz);
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/popPage.action")
	public ModelAndView getPopPage(){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		String _page = "popMain";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(!isManageJob(userid)){				
				_page="popDetail";
			}					
		}
		return new ModelAndView("/medical/medical_anti_dose/"+_page);
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<BaseInpatient> getListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){	
			if(isManageJob(userid)){
				addJobDeptConditionToMap(userid,map,"dept_code");
			}else{
				addUsridConditionToMap(userid,map,"doct_code");
			}
			//查找科室数据		
		}
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDeptListDomain.action")
	public ListDomain<BaseInpatient> getDeptListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(isManageJob(userid)){
				addJobDeptConditionToMap(userid,map,"dept_code");
			}else{
				addUsridConditionToMap(userid,map,"doct_code");
			}			
			//查找科室数据		
		}
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		if(!paramMap.containsKey("data_type"))
			paramMap.put("data_type", "1");		
		
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}

	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	
	private List<BaseInpatient> getList(String monitor_year_month){
		
		String sql = String.format("select * from %1$s where monitor_year_month='%2$s'",this.tableName,monitor_year_month); 
		//查询表
		return super.getAllList(sql);
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	
	private List<BaseInpatient> getList(String st, String en){
		
		String sql = String.format("select * from %1$s where outhospitalat is null or (outhospitalat >= to_date('%2$s 00:00:00', 'yyyy-mm-dd hh24:mi:ss') and outhospitalat <= to_date('%3$s 23:59:59', 'yyyy-mm-dd hh24:mi:ss'))",
				this.tableName, st, en); 
		//查询表
		return super.getAllList(sql);
		
	}
	
	/**
	 * 查询实时数据
	 * @param body
	 * @return
	 */
	@RequestMapping("/getRealTimeListDomain.action")
	public ListDomain<BaseInpatient> getRealTimeListDomain(@RequestBody(required=false) String body){		
		Map<String,Object> paramMap = this.getBodyParam(body);
		
		String[] monitorDate = super.getMonitorDate(paramMap);
		if(monitorDate!=null && monitorDate.length>1){			
			
			String start = monitorDate[0];
			String end = monitorDate[1];
			String year_month = monitorDate[2];
			List<BaseInpatient> inlists =countMedicalInpatient (year_month,start,end,null);
			
			
			if(inlists!=null ){				
//				BaseInpatientService.save(inlists);
				return super.getListDomainByConditionAndOrderUseTable(body, typeMap, orderMap,true);
			}					
			
		}
		//查询表
		
		return new ListDomain<BaseInpatient>();
	}
	
	/**
	 * 执行自动统计
	 */
	public List<BaseInpatient> autoMonitor(Integer yearF, Integer monthF, Integer dayF, Integer yearT, Integer monthT,
			Integer dayT){
		
		String[] yesterday = getParamDate(yearF, monthF, dayF, yearT, monthT, dayT);
		
		List<BaseInpatient> inlists = countMedicalInpatient(yesterday[0],yesterday[1],yesterday[2],null);
		
		
		List<BaseInpatient> oldLists = this.getList(yesterday[1], yesterday[2]);
		LinkedHashMap<String,BaseInpatient> lmap = new LinkedHashMap<String,BaseInpatient>();
		
		//将已有值存入临时map
		if(oldLists!=null && oldLists.size()>0){
			
			for(int i=0;i<oldLists.size();i++){
				BaseInpatient b = oldLists.get(i);
				String _key = null;
				//以下部分需要字段支持
				if(b.getPatient_id() != null && b.getPatient_no() != null){
					_key = b.getPatient_id() + "-" + b.getPatient_no();
					lmap.put(_key, b);
				}
				_key = b.getPatient_id() + "-" + b.getPatient_no();
				lmap.put(_key, b);
			}
		}
		
		
		if(inlists!=null ){
			
			if(lmap!=null && lmap.size()>0){
				for(int i=0;i<inlists.size();i++){
					BaseInpatient b = inlists.get(i);
					String _key = null;
					//以下部分需要字段支持
					if(b.getPatient_id() != null && b.getPatient_no() != null){
						_key = b.getPatient_id() + "-" + b.getPatient_no();
						if(lmap.containsKey(_key)){
							inlists.get(i).setId(lmap.get(_key).getId());
						}
						else{
							System.out.println("here a mess found");
						}
					}
				}
			}
			
//			BaseInpatientService.save(inlists);			
		}	
		return inlists;
	}
	
	private String[] getParamDate(Integer yearF, Integer monthF, Integer dayF, Integer yearT, Integer monthT,
			Integer dayT) {
		// TODO Auto-generated method stub
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, -1);
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DATE);
		if(yearT == null || monthT == null || dayT == null){
			yearT = year;
			monthT = month;
			dayT = day;
		}
		if(yearF == null || monthF == null || dayF == null){
			yearF = year;
			monthF = month;
			dayF = day;
		}
		String[] ret = {
				year + "-" + month,
				yearF + "-" + monthF + "-" + dayF,
				yearT + "-" + monthT + "-" + dayT
		};
		return ret;
	}


	
	
	/**
	 * 统计住院患者抗菌药物使用情况
	 * @param year_month
	 * @param startDate
	 * @param endDate
	 * @param countType	0,期间出院病人;1,期间在院病人
	 * @return
	 */
	public List<BaseInpatient> countMedicalInpatient(String year_month,String startDate ,String endDate,String countType){
		
		String sql_total_price = qryDictionaryService.getSqlByBizcode("medical_base_inpatient_total_price");
		List<BaseInpatient> allLists = null;
		
		if(sql_total_price != null && sql_total_price.trim().length() > 0){
			allLists = getAllList(String.format(sql_total_price, startDate, endDate));
		}
		else{
			return new LinkedList<>();
		}
		HashMap<String, BaseInpatient> allMap = listToMap(allLists);
		
		//出院病人统计语句
		String sqlHead= "medical_base_inpatient_";
		
		//统计全院数据-住院
		
		List<String> sqls = new ArrayList<String>();
		String[] indexs = {"bed_days", "nursing_days", "examine_days", "grave_hours", "oxygen_days", "total_base_price", "total_anti_price", "drug_price", "ddd"};
//		int index = 0;
		for(String indexStr:indexs){
			String sql = qryDictionaryService.getSqlByBizcode(sqlHead + indexStr);
			sql = String.format(sql,startDate,endDate);
			List<BaseInpatient> tmpLists = getAllList(sql);
			if(tmpLists!=null && tmpLists.size()>0){
				for(BaseInpatient a: tmpLists){
					if(a.getPatient_id() != null && a.getPatient_no() != null){
						String key = a.getPatient_id() + "-" + a.getPatient_no();
						if(allMap.containsKey(key)){
							switch(indexStr){
							case "bed_days":
								allMap.get(key).setBed_days(a.getBed_days());
								break;
							case "nursing_days":
								allMap.get(key).setNursing_days(a.getNursing_days());
								break;
							case "examine_days":
								allMap.get(key).setExamine_days(a.getExamine_days());
								break;
							case "grave_hours":
								allMap.get(key).setGrave_hours(a.getGrave_hours());
								break;
							case "oxygen_days":
								allMap.get(key).setOxygen_days(a.getOxygen_days());
								break;
							case "total_base_price":
								allMap.get(key).setTotal_base_price(a.getTotal_base_price());
								break;
							case "total_anti_price":
								allMap.get(key).setTotal_anti_price(a.getTotal_anti_price());
								break;
							case "drug_price":
								allMap.get(key).setDrug_price(a.getDrug_price());
								break;
							case "ddd":
								allMap.get(key).setDdd(a.getDdd());
								break;
							}
						}
					}
				}
			}
		}
		
		LinkedList<BaseInpatient> lists = new LinkedList<>();
		
		for(String key: allMap.keySet()){
			lists.add(allMap.get(key));
		}
		//所有数据
		
		return lists;
		
	}
	
	
	
	
	
	private HashMap<String, BaseInpatient> listToMap(List<BaseInpatient> allLists) {
		// TODO Auto-generated method stub
		HashMap<String, BaseInpatient> allMap = new HashMap<>();
		
		for(BaseInpatient a: allLists){
			if(a.getPatient_id() != null && a.getPatient_no() != null){
				allMap.put(a.getPatient_id() + "-" + a.getPatient_no(), a);
			}
		}
		return allMap;
	}

	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public BaseInpatient getOne(@RequestParam(value="id",required=false) Long id){
				
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public BaseInpatient getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
}
